const { regeneratorRuntime, md5 } = global

Page(global.connect(
  state => ({
    ...state.globalReducer,
    ...state.profileReducer
  }),
  dispatch => ({
    // 获取验证码
    async handleGetSMSCode(e) {
      console.log('handleGetSMSCode')
      if (this.data.uiCodeCount === 60) {
        const actionRes = await dispatch(global.profileReducer.getAuditSendCode({
          phone: this.data.phone
        }))
        if (actionRes.actionStatus !== 'SUCCESS') {
          this.selectComponent('#toast').handleShow({
            message: actionRes.apiMes
          })
        }
      }
    },
    // 注册提交
    async handleSubmit(e) {
      console.log('handleSubmit', e)
      const {
        phone, password, sms_code, invite_code,
        jobs
      } = this.data

      // 简单校验
      const specialties = jobs.filter(i => i.selected).map(i => i.value).join(',')
      const openid = wx.getStorageSync('openid')
      const formData = { phone, password, sms_code, invite_code, specialties, openid }
      console.log('formData', formData)
      if (!phone || !password || !sms_code || !invite_code || !specialties || !openid) {
        this.showToast({ message: '请填写完整信息' })
        return
      }
      formData.password = md5(formData.password)

      // 注册
      try {
        const actionRes = await dispatch(global.profileReducer.userRegist(formData))

        console.log(actionRes)
        if (actionRes.actionStatus === 'SUCCESS') {
          this.selectComponent('#toast').handleShow({
            type: 'success',
            message: actionRes.apiMes
          })
          setTimeout(() => {
            // 同步数据
            dispatch(global.globalReducer.asyncRegistInfo(actionRes.data))

            global.handleRoute({ route: 'auth', type: 'redirectTo' })
          }, 1000);
        } else {
          this.selectComponent('#toast').handleShow({
            message: actionRes.apiMes || '注册失败，请稍后再试'
          })
        }
      } catch (error) {
        this.selectComponent('#toast').handleShow({
          message: error.apiMes || '注册失败，请稍后再试'
        })
      }
    }
  })
)({
  data: {
    phone: '',
    password: '',
    sms_code: '',
    invite_code: '',
    jobs: [
      { name: '车身广告安装', value: 1, selected: false },
      { name: '店铺广告安装', value: 2, selected: false },
      { name: '标识标牌', value: 3, selected: false },
    ]
  },
  showToast({ type, message }) {
    this.selectComponent('#toast').handleShow({ type, message })
  },
  handleField(e) {
    const obj = {}
    obj[e.currentTarget.dataset.field] = e.detail.value
    this.setData(obj)
  },
  handleGetCode(e) {
    this.showToast({ message: '请填写完整信息' })
  },
  handleSelectGoodJob(e) {
    const { jobs } = this.data
    const { index } = e.currentTarget.dataset
    jobs[index].selected = !jobs[index].selected
    this.setData({ jobs })
  },
  handleLicon1Tap(e) {
    wx.navigateBack()
  },
}))
